/*
 *  The MIT License
 *
 * Copyright (c) 2010, Seiji Sogabe
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
package hudson.plugins.googlecodetrigger;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;

/**
 *
 * @author sogabe
 */
public class AuthenticationKey {

    private final String secret;

    public AuthenticationKey(String key) {
        this.secret = key;
    }

    public boolean validate(String expectedHash, String payload) {
        if (expectedHash == null) {
            return false;
        }
        LOGGER.fine("Authentication Key: " + secret);
        LOGGER.fine("payload: " + payload);
        LOGGER.fine("expectedHash: " + expectedHash);

        try {
            Key key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance(key.getAlgorithm());
            mac.init(key);
            byte[] digest = mac.doFinal(payload.getBytes("UTF-8"));
            String calculatedHash = new String(Hex.encodeHex(digest));
            LOGGER.fine("calculatedHash: " + calculatedHash);
            return expectedHash.equals(calculatedHash);
        } catch (InvalidKeyException ex) {
            LOGGER.warning(ex.getMessage());
            return false;
        } catch (UnsupportedEncodingException ex) {
            LOGGER.warning(ex.getMessage());
            return false;
        } catch (NoSuchAlgorithmException ex) {
            LOGGER.warning(ex.getMessage());
            return false;
        }
    }

    private static final Logger LOGGER = Logger.getLogger(AuthenticationKey.class.getName());
}
